<?php

namespace app\api\service;

use app\common\model\ScienceModel;
use app\common\model\ScienceCategoryModel;
use app\common\model\ScienceLikeModel;

class ScienceService
{
    /**
     * 格式化文章数据
     * @param array $article 文章数据
     * @param int $uid 用户ID（可选，用于判断关注状态）
     * @return array 格式化后的文章数据
     */
    public static function formatArticle($article, $uid = 0)
    {
        if (empty($article)) {
            return [];
        }
        
        // 处理关联的分类数据
        if (isset($article['category']) && !empty($article['category'])) {
            $category = $article['category'];
            $article['category_name'] = $category['name'];
            // 保留原始的category关联数据，同时添加category_name字段
        } else if (isset($article['category_id'])) {
            // 如果没有关联数据但有category_id，尝试通过ID获取分类名称
            $category = ScienceCategoryModel::where('id', $article['category_id'])->find();
            if ($category) {
                $article['category_name'] = $category['name'];
            }
        }
        
        // 格式化发布时间
        if (isset($article['publish_time']) && $article['publish_time']) {
            $article['publish_time_format'] = date('Y-m-d', $article['publish_time']);
        } else {
            $article['publish_time_format'] = '';
        }
        
        // 格式化浏览量和点赞数
        if (isset($article['views'])) {
            $article['views_str'] = self::formatNumber($article['views']);
        }
        
        if (isset($article['likes'])) {
            $article['likes_str'] = self::formatNumber($article['likes']);
        }
        
        // 处理封面图
        if (isset($article['cover_image']) && !empty($article['cover_image'])) {
            // 确保封面图是完整的URL
            if (strpos($article['cover_image'], 'http://') === false && strpos($article['cover_image'], 'https://') === false) {
                $article['cover_image'] = request()->domain() . '/' . ltrim($article['cover_image'], '/');
            }
        }
        $article['is_following'] = 0;
        // 处理用户关注状态
        if ($uid > 0 && isset($article['user_id'])) {
            try {
                // 检查是否存在关注关系表
                $followModel = 'app\\common\\model\\user\\FollowModel';
                if (class_exists($followModel)) {
                    $isFollowing = $followModel::where('user_id', $uid)
                        ->where('follow_id', $article['user_id'])
                        ->count() > 0;
                    $article['is_following'] = $isFollowing ? 1 : 0;
                }
            } catch (\Exception $e) {
                // 如果关注表不存在或查询出错，默认设置为未关注
                $article['is_following'] = 0;
            }
        }
        
        // 处理用户点赞状态
        if ($uid > 0 && isset($article['id'])) {
            try {
                $isLiked = ScienceLikeModel::where('user_id', $uid)
                    ->where('article_id', $article['id'])
                    ->count() > 0;
                $article['is_liked'] = $isLiked ? 1 : 0;
            } catch (\Exception $e) {
                // 如果查询出错，默认设置为未点赞
                $article['is_liked'] = 0;
            }
        }
        
        return $article;
    }
    
    /**
     * 格式化数字，将大数字转换为带单位的格式
     * @param int $num 数字
     * @return string 格式化后的数字字符串
     */
    public static function formatNumber($num)
    {
        if ($num >= 10000) {
            return sprintf('%.1f万', $num / 10000);
        }
        return (string) $num;
    }
    
    /**
     * 获取热门文章列表
     * @param int $limit 获取数量
     * @return array 热门文章列表
     */
    public static function getHotArticles( $uid = 0, $page = 1, $size = 10)
    {
       $query = ScienceModel::where('status', 1)
            ->with(['category' => function($query) {
                $query->field('id, name');
            },'user' => function($query) {
                $query->field('id, name, avatar');
            }]);
        
      
        
        $count = $query->count();
        $list = $query->order('publish_time', 'desc')
            ->page($page, $size)
            ->field('id, title, source, views, likes, publish_time, cover_image, category_id, user_id, disclaimer')
            ->select();
        // 使用服务层格式化数据
        $formattedList = [];
        foreach ($list as $article) {
            $formattedList[] = ScienceService::formatArticle($article->toArray(), $uid);
        }
        
       

        return [
            'list' => $formattedList,
            'total' => $count,
            'page' => $page,
            'size' => $size
        ];
    }
    
    /**
     * 搜索文章
     * @param string $keyword 搜索关键词
     * @param int $page 页码
     * @param int $size 每页数量
     * @return array 搜索结果
     */
    public static function searchArticles($keyword, $page = 1, $size = 10)
    {
        if (empty($keyword)) {
            return [
                'list' => [],
                'total' => 0,
                'page' => $page,
                'size' => $size
            ];
        }
        
        $query = ScienceModel::where('status', 1)
            ->where('title', 'like', '%' . $keyword . '%');
        
        $count = $query->count();
        $list = $query->order('publish_time', 'desc')
            ->page($page, $size)
            ->field('id, title, source, views, likes, publish_time, cover_image, category_id, category_name')
            ->select();
        
        $result = [];
        foreach ($list as $article) {
            $result[] = self::formatArticle($article->toArray());
        }
        
        return [
            'list' => $result,
            'total' => $count,
            'page' => $page,
            'size' => $size
        ];
    }
}